﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace FFSupplier.Common.TKCommon
{
    public class WebAPICommon:IWebAPICommon
    {
        ICrmConfiguration _crmConfiguration;
        Dynamics365WebApiHelper _dynamics365WebApiHelper;


        public WebAPICommon(ICrmConfiguration crmConfiguration, Dynamics365WebApiHelper dynamics365WebApiHelper)
        {
            _crmConfiguration = crmConfiguration;
            _dynamics365WebApiHelper = dynamics365WebApiHelper;
        }


        public async Task createNRelationShip(string targetEntityName, string targetEntityId, string relatedEntityName, string relatedTargetId, string relatedName)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            string weburi = _crmConfiguration.getWebUrl();

            dic.Add("@odata.id", weburi + relatedEntityName + "(" + relatedTargetId.Replace("{", "").Replace("}", "") + ")");

            using (HttpClient httpClient = _dynamics365WebApiHelper.GetHttpClientWithCredential())
            {
                var content = new StringContent(JsonConvert.SerializeObject(dic), Encoding.UTF8, "application/json");
                var result = await httpClient.PostAsync(weburi, content);

            }
        }

        public async Task<Guid> createRecord(JObject entityobject, string entityNames)
        {
            Guid guid = Guid.Empty;
            string createUrl = string.Format(_crmConfiguration.getWebUrl() + entityNames);
            var createStr = JsonConvert.SerializeObject(entityobject);
            var content = new StringContent(createStr, Encoding.UTF8, "application/json");
            using (HttpClient client = _dynamics365WebApiHelper.GetHttpClientWithCredential())
            {
                HttpResponseMessage createResponse = await client.PostAsync(createUrl, content);
                string accountUri = string.Empty;
                var result = await createResponse.Content.ReadAsStringAsync();

                if (createResponse.IsSuccessStatusCode)
                {
                    accountUri = createResponse.Headers.GetValues("OData-EntityId").FirstOrDefault();
                    guid = new Guid(accountUri.Substring(accountUri.Length - 37, 36));
                }
                else
                {
                    var errorMsg = await createResponse.Content.ReadAsStringAsync();
                    throw new Exception(createStr + errorMsg);
                }



            }
            return guid;
        }

        public async Task deleteLookUpProperty(string guid, string entityName, string propertyName)
        {
            string weburi = _crmConfiguration.getWebUrl() + entityName + "(" + guid.Replace("{", "").Replace("}", "") + ")/" + propertyName + "/$ref";
            using (HttpClient httpClient = _dynamics365WebApiHelper.GetHttpClientWithCredential())
            {
                var result = await httpClient.DeleteAsync(weburi);
                string resultContent = await result.Content.ReadAsStringAsync();
            }
        }

        public async Task deleteNRelationShip(string targetEntityName, string targetEntityId, string relatedEntityName, string relatedTargetId, string relatedName)
        {
            string weburi = _crmConfiguration.getWebUrl();
            weburi = weburi + targetEntityName + "(" + targetEntityId.Replace("{", "").Replace("}", "") + ")/" + relatedName + "/$ref?$id=" + weburi + relatedEntityName + "(" + relatedTargetId.Replace("{", "").Replace("}", "") + ")";
            using (HttpClient httpClient = _dynamics365WebApiHelper.GetHttpClientWithCredential())
            {
                var result = await httpClient.DeleteAsync(weburi);
                string resultContent = await result.Content.ReadAsStringAsync();

            }
        }

        public async Task deleteOneProperty(string guid, string entityName, string propertyName)
        {
            string weburi = _crmConfiguration.getWebUrl() + entityName + "(" + guid.Replace("{", "").Replace("}", "") + ")/" + propertyName;
            using (HttpClient httpClient = _dynamics365WebApiHelper.GetHttpClientWithCredential())
            {
                var result = await httpClient.DeleteAsync(weburi);
                string resultContent = await result.Content.ReadAsStringAsync();

            }
        }

        public async Task deleteRecord(string guid, string entityName)
        {
            string weburi = _crmConfiguration.getWebUrl() + entityName + "(" + guid.Replace("{", "").Replace("}", "") + ")";
            using (HttpClient httpClient = _dynamics365WebApiHelper.GetHttpClientWithCredential())
            {
                var result = await httpClient.DeleteAsync(weburi);
                string resultContent = await result.Content.ReadAsStringAsync();
            }
        }

        public async Task<string> retrieveMultipleByFilter(string entityNames, string filter)
        {
            string result = "";

            string webApiUrl = _crmConfiguration.getWebUrl() + entityNames;
            if (!string.IsNullOrEmpty(filter))
            {
                webApiUrl = webApiUrl + filter;
            }
            using (HttpClient httpClient = _dynamics365WebApiHelper.GetHttpClientWithCredential())
            {


                try
                {
                    httpClient.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");
                    //HttpResponseMessage response = await httpClient.GetAsync(webApiUrl);
                    //result = await response.Content.ReadAsStringAsync();
                    //远程获取数据
                    var task = httpClient.GetAsync(webApiUrl);
                    var rep = task.Result;//在这里会等待task返回。

                    //读取响应内容
                    var task2 = rep.Content.ReadAsStringAsync();
                    result = task2.Result;//在这里会等待task返回。

                }
                catch (Exception ex)
                {

                    throw;
                }

            }
            return result;
        }
        public async Task<JArray> retrieveMultiplePageing(string uri, string count, JArray jArray)
        {
            var result = "";

            using (HttpClient httpClient = _dynamics365WebApiHelper.GetHttpClientWithCredential())
            {
                httpClient.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue,odata.maxpagesize=" + count);
                HttpResponseMessage response = await httpClient.GetAsync(uri);
                result = await response.Content.ReadAsStringAsync();

                JObject jObject = (JObject)JsonConvert.DeserializeObject(result.ToString());

                if (((JArray)jObject["value"]).Count > 0)
                {
                    jArray.Add(jObject.SelectToken("value"));
                }

                if (result.ToString().Contains("@odata.nextLink"))
                {
                    await retrieveMultiplePageing(((JArray)jObject["@odata.nextLink"]).ToString(), count, jArray);
                }
            }
            return jArray;
        }

        public async Task<string> retrieveOneProperty(string guid, string entityNames, string propertyName)
        {
            string result = "";
            string weburi = _crmConfiguration.getWebUrl() + entityNames + "(" + guid.Replace("{", "").Replace("}", "") + ")/" + propertyName;
            using (HttpClient httpClient = _dynamics365WebApiHelper.GetHttpClientWithCredential())
            {
                httpClient.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");
                HttpResponseMessage response = await httpClient.GetAsync(weburi);
                result = await response.Content.ReadAsStringAsync();
            }
            return result;
        }

        public async Task<string> retrieveRecord(string guid, string entityNames, string xName)
        {
            string result = "";
            string weburi = _crmConfiguration.getWebUrl() + entityNames + "(" + guid.Replace("{", "").Replace("}", "") + ")";
            if (!string.IsNullOrEmpty(xName))
            {
                weburi = weburi + xName;
            }
            using (HttpClient httpClient = _dynamics365WebApiHelper.GetHttpClientWithCredential())
            {
                try
                {
                    httpClient.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");
                    HttpResponseMessage response = await httpClient.GetAsync(weburi);
                    result = await response.Content.ReadAsStringAsync();
                }
                catch (Exception ex)
                {

                    throw;
                }

            }
            return result;
        }

        public async Task<string> retrieveRecordByFechXml(string entityNames, string fetchxml)
        {
            string result = "";
            string webApiUrl = _crmConfiguration.getWebUrl();
            webApiUrl = webApiUrl + entityNames + "?fetchXml=" + Uri.EscapeUriString(fetchxml);
            using (HttpClient httpClient = _dynamics365WebApiHelper.GetHttpClientWithCredential())
            {

                httpClient.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");
                HttpResponseMessage response = await httpClient.GetAsync(webApiUrl);
                result = await response.Content.ReadAsStringAsync();
            }
            return result;
        }

        public async Task updateRecord(string guid, JObject entityObject, string entityNames)
        {
            string weburi = _crmConfiguration.getWebUrl() + entityNames + "(" + guid.Replace("{", "").Replace("}", "") + ")";
            HttpRequestMessage uptReq = new HttpRequestMessage(new HttpMethod("PATCH"), weburi);

            var updateContent = JsonConvert.SerializeObject(entityObject);

            uptReq.Content = new StringContent(updateContent, Encoding.UTF8, "application/json");
            HttpClient client = _dynamics365WebApiHelper.GetHttpClientWithCredential();
            HttpResponseMessage uptResp = await client.SendAsync(uptReq);

            if (uptResp.IsSuccessStatusCode)
            {
                Console.WriteLine("Update Successfully");
            }
            else
            {
                var errorMsg = await uptResp.Content.ReadAsStringAsync();
                throw new Exception(errorMsg + updateContent);
            }
        }

        public async Task updateRecordOneProperty(string guid, string entityName, string propertyName, string propertyValue)
        {
            string weburi = _crmConfiguration.getWebUrl() + entityName + "(" + guid.Replace("{", "").Replace("}", "") + ")/" + propertyName;

            using (HttpClient httpClient = _dynamics365WebApiHelper.GetHttpClientWithCredential())
            {
                httpClient.Timeout = new TimeSpan(0, 2, 0);  // 2 minutes  

                var content = new StringContent(propertyValue, Encoding.UTF8, "application/json");
                HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("PUT"), weburi);
                request.Content = content;

                var result = await httpClient.SendAsync(request);//.PutAsync(weburi, content).Result;
                string resultContent = await result.Content.ReadAsStringAsync();

            }
        }

        /// <summary> Displays formatted entity collections to the console. </summary>  
        /// <param name="label">Descriptive text output before collection contents </param>  
        /// <param name="collection"> JObject containing array of entities to output by property </param>  
        /// <param name="properties"> Array of properties within each entity to output. </param>  
        public string DisplayFormattedEntities(JObject entity, string prop)
        {
            string propValue = "";
            List<string> propsOutput = new List<string>();
            //Iterate through each requested property and output either formatted value if one   
            //exists, otherwise output plain value.  
            string formattedProp = prop + "@OData.Community.Display.V1.FormattedValue";
            if (null != entity[formattedProp])
            { propValue = entity[formattedProp].ToString(); }
            else
            { propValue = entity[prop].ToString(); }
            propsOutput.Add(propValue);

            return propValue;
        }

        public async Task<string> retrieveMultipleByLink(string link)
        {
            string result = "";

            // string webApiUrl = _crmConfiguration.getWebUrl() + entityNames;

            using (HttpClient httpClient = _dynamics365WebApiHelper.GetHttpClientWithCredential())
            {


                try
                {
                    httpClient.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");
                    HttpResponseMessage response = await httpClient.GetAsync(link);
                    result = await response.Content.ReadAsStringAsync();


                }
                catch (Exception ex)
                {

                    throw ex;
                }

            }
            return result;
        }

        public string retrieveMultipleByFilterNonAsync(string entityNames, string filter)
        {
            string result = "";

            string webApiUrl = _crmConfiguration.getWebUrl() + entityNames;
            if (!string.IsNullOrEmpty(filter))
            {
                webApiUrl = webApiUrl + filter;
            }
            using (HttpClient httpClient = _dynamics365WebApiHelper.GetHttpClientWithCredential())
            {


                try
                {
                    httpClient.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");
                    HttpResponseMessage response = httpClient.GetAsync(webApiUrl).Result;
                    result = response.Content.ReadAsStringAsync().Result;


                }
                catch (Exception ex)
                {

                    throw;
                }

            }
            return result;
        }
    }
}